import fs from "fs"
import path from "path"
import { exec } from "child_process"
import { Buffer } from "buffer"

export default function viteExportJsonPlugin() {
    return {
        name: "vite-export-json-plugin",
        configureServer(server) {
            server.middlewares.use("/export-json", (req, res) => {
                if (req.method !== "POST") {
                    res.statusCode = 405
                    return res.end("Method Not Allowed")
                }

                let body = []
                req.on("data", (chunk) => {
                    body.push(chunk)
                }).on("end", () => {
                    try {
                        const data = Buffer.concat(body).toString()
                        const jsonData = JSON.parse(data)

                        // 获取文件名，如果没有提供则使用默认名
                        let filename = req.headers["x-file-name"] ? decodeURIComponent(req.headers["x-file-name"]) : `export-${Date.now()}.json`

                        // 确保文件名以.json结尾
                        if (!filename.endsWith(".json")) {
                            filename += ".json"
                        }

                        // 保存到项目根目录下的 exportJson 文件夹
                        const rootDir = process.cwd()
                        const resDir = path.join(rootDir, "exportJson")

                        // 如果文件夹不存在，则创建
                        if (!fs.existsSync(resDir)) {
                            fs.mkdirSync(resDir)
                        }

                        // 拼接文件路径
                        const filePath = path.join(resDir, filename)

                        // 写入文件
                        fs.writeFileSync(
                            filePath,
                            JSON.stringify(jsonData, null, 2) // 美化输出
                        )

                        // 打开文件管理器
                        try {
                            if (process.platform === "win32") {
                                exec(`explorer /select,"${filePath}"`)
                            } else if (process.platform === "darwin") {
                                exec(`open -R "${filePath}"`)
                            } else {
                                // Linux或其他Unix-like系统
                                exec(`xdg-open "${resDir}"`)
                            }
                        } catch (openError) {
                            console.warn("Could not open file manager:", openError)
                        }

                        // 返回成功响应
                        res.setHeader("Content-Type", "application/json")
                        res.end(
                            JSON.stringify({
                                success: true,
                                filename: filename,
                                path: filePath,
                                message: `File saved and opened in file manager`,
                            })
                        )
                    } catch (error) {
                        console.error("Export error:", error)
                        res.statusCode = 500
                        res.setHeader("Content-Type", "application/json")
                        res.end(
                            JSON.stringify({
                                success: false,
                                error: error.message,
                            })
                        )
                    }
                })
            })
        },
    }
}
